//
//  MultiFunctionCell.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/7/9.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import SwiftyJSON

@objc protocol MultiFunctionDelegate: class {
    @objc optional func dropDownClick(sender: UIButton,  cellIndex: IndexPath, tableTag: Int)  //
    @objc optional func circularClick(sender: UITapGestureRecognizer,  cellIndex: IndexPath, tableTag: Int)
    @objc optional func switchChange(sender: UISwitch,  cellIndex: IndexPath, tableTag: Int)
    @objc optional func buttonClick(sender: UIButton, cellIndex: IndexPath, tableTag: Int)
    @objc optional func radioClick(sender: UIButton, cellIndex: IndexPath, tableTag: Int)
    @objc optional func fieldChange(sender: UITextField, text:String,cellIndex: IndexPath, tableTag: Int)
    
}


class MultiFunctionCell: HMTableViewCell {

    enum MFC_TYPE: String {
        case label  = "label"
        case button = "button"
        case dropDown = "dropDown"
        case circular = "circular"
        case field = "field"
        case `switch` = "switch"
        case radio = "radio"  //单选
        case checkbox = "checkbox" //多选
    }
   
    // MARK: - 变量
    var MFC_view: UIView?
    var type: MFC_TYPE = .label  //默认
    weak var delegate: MultiFunctionDelegate?
    var MFC_Switch: UISwitch?
    var MFC_switchLabel: UILabel?
    var MFC_Field: UITextField?
    var MFC_fieldLable: UILabel?
    var MFC_Circular: UIImageView?
    var MFC_Button: UIButton?
    var MFC_DropDown: UIButton?
    var MFC_label: UILabel?
    var MFC_Radio: Array<UIButton>? //单选择
    var MFC_checkbox: [UIButton]? //多选
    
    var MFC_cellHeight: CGFloat?   //cell 高度
    //
    var MFC_indexPath: IndexPath? // 记录某个cell
    var MFC_tableTag: Int = 0 // 记录ttable tag

    
    private var radioBtnIndex: Int = 0  //单选默认值
    // MARK: - 常量
   
    
    
    // MARK: - switch
     /**
        switch 初始化
      */
    func addSwitchCell(title: String, isOn: Bool) {
        removeAll()
        
        let switchButton = UISwitch()
        let titleLabel = UILabel()
        
        self.addSubview(switchButton)
        self.addSubview(titleLabel)
        
        
        titleLabel.topAlign(view: self)
        titleLabel.bottomAlign(view: self)
        titleLabel.leadingAlign(view: self, predicate: "20")
        
        
        switchButton.centerXYAlign(view: titleLabel)
//        switchButton.leadingHorizontally(view: titleLabel, predicate: "20")
        switchButton.trailingAlign(view: self, predicate: "-20")
        switchButton.addTarget(self, action: #selector(switchChange), for: .valueChanged)
        
        MFC_Switch = switchButton
        MFC_switchLabel = titleLabel
//        return (switchButton,titleLabel)
    }
    
    func removeSwitchCell()  {
        MFC_Switch?.removeFromSuperview()
        MFC_switchLabel?.removeFromSuperview()
    }
    
    @objc func switchChange(sender: UISwitch) {
        delegate?.switchChange!(sender: sender, cellIndex: MFC_indexPath!, tableTag: MFC_tableTag)
    }
    
    // MARK: - field
    /**
     field
     */
    func addFieldCell(title: String, placeholder: String) {
        removeAll()
        
        let field = UITextField()
        let describe = UILabel()
        let fieldLeftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 0))
        field.placeholder =  placeholder
        
        self.addSubview(describe)
        self.addSubview(field)
        
        describe.topAlign(view: self)
        describe.leadingAlign(view: self, predicate: "20")
        describe.trailingAlign(view: self, predicate: "-20")
        describe.height(view: self, predicate: "*0.3")
        describe.font = configure.shareConfigure.HMSize_15
        describe.text = "描述。。。。。"
        field.topVertically(view: describe, predicate: "8")
        field.bottomAlign(view: self)
        field.leadingAlign(view: self, predicate: "20")
        field.trailingAlign(view: self, predicate: "-20")
        field.layer.borderWidth = 1.0
        field.layer.borderColor = configure.shareConfigure.HMColor2.cgColor
        field.layer.cornerRadius = 3.0
        field.setValue(configure.shareConfigure.HMSize_15, forKeyPath: "_placeholderLabel.font")
        field.delegate = self
        field.text = title
        
        fieldLeftView.backgroundColor = UIColor.white
        field.leftView = fieldLeftView
        field.leftViewMode = UITextFieldViewMode.always //一直存在
       
        MFC_fieldLable = describe
        MFC_Field = field
    }
    func removeFieldCell()  {
        MFC_fieldLable?.removeFromSuperview()
        MFC_Field?.removeFromSuperview()
    }
    
    // MARK: - circular
    /**
     circular
     */
    func addCircularCell(img: UIImage) {
        removeAll()
        
        let imageButton = UIImageView()
        let gesture = UITapGestureRecognizer(target: self, action: #selector(imageTap))
        
        self.addSubview(imageButton)
        self.addGestureRecognizer(gesture)
        
        imageButton.image =  img//UIImage(named: "pl.png")
//        imageButton.leadingAlign(view: self, predicate: "20")
//        imageButton.trailingAlign(view: self, predicate: "-20")
//        imageButton.topAlign(view: self)
//        imageButton.bottomAlign(view: self)
        imageButton.centerXYAlign(view: self)
        let h  =  self.wHeight - 5
        imageButton.heightConstrain(predicate: "\(h)")
        imageButton.widthConstrain(predicate: "\(h)")
        
        MFC_Circular = imageButton
    }
    func removeCircularCell() {
        MFC_Circular?.removeFromSuperview()
    }
    
    @objc func imageTap(sender: UITapGestureRecognizer) {
        delegate?.circularClick!(sender: sender, cellIndex: MFC_indexPath!, tableTag: MFC_tableTag)
    }
    
    // MARK: - button
    /**
     button
     */
    func addButtonCell(title: String?) {
        removeAll()
        
        let  button = UIButton()
        button.setTitle(title, for: .normal)
        self.addSubview(button)
       
        button.topAlign(view: self, predicate: "8")
        button.bottomAlign(view: self, predicate: "-8")
        button.leadingAlign(view: self, predicate: "20")
        button.trailingAlign(view: self, predicate: "-20")
        button.addTarget(self, action: #selector(buttonClick), for: UIControlEvents.touchUpInside)
        button.setTitleColor(UIColor.white, for: .normal)
        button.layer.borderWidth = 1.0
        button.layer.borderColor = configure.shareConfigure.HMColor1.cgColor
        button.layer.cornerRadius = 3.0
        button.titleLabel?.font = configure.shareConfigure.HMSize_15
        button.backgroundColor = configure.shareConfigure.HMColor1
        
        MFC_Button = button
    }
    func removeButtonCell() {
        MFC_Button?.removeFromSuperview()
    }
    
    @objc func buttonClick(sender: UIButton) {
        //提交
        delegate?.buttonClick!(sender: sender, cellIndex: MFC_indexPath!, tableTag: MFC_tableTag)
    }
    // MARK: - dropDown
    /**
     dropDown
     */
    func addDropDownCell(title: String) {
        removeAll()
        
        let button = UIButton()
        button.setTitle(title, for: .normal)
        
        self.addSubview(button)
//        button.topAlign(view: self)
//        button.bottomAlign(view: self)
        
        button.topAlign(view: self)
        button.bottomAlign(view: self)
        
        button.leadingAlign(view: self, predicate: "20")
        button.trailingAlign(view: self, predicate: "-20")
        
        
//        button.setBackgroundImage(UIImage(named: "dropDown.png"), for: .normal)
        button.layer.borderWidth = 1.0
        button.layer.borderColor = configure.shareConfigure.HMColor2.cgColor
        button.layer.cornerRadius = 3.0
        button.setTitleColor(UIColor.black, for: .normal)
        button.titleLabel?.font = configure.shareConfigure.HMSize_15
        button.titleEdgeInsets = UIEdgeInsetsMake(0, -50, 0, 0);
        button.addTarget(self, action: #selector(dropDown(sender:)), for: UIControlEvents.touchUpInside)
        
        
        let h =  self.wHeight - 16
        let sub = UIImageView.init(image: UIImage.init(named: "xianjiang.png"))
        button.addSubview(sub)
        sub.centerYAlign(view: button)
        sub.trailingAlign(view: button, predicate: "-14")
        sub.heightConstrain(predicate: "\(h - 26)")
        sub.widthConstrain(predicate: "\(h - 18)")

        //        button.layer.masksToBounds = true
        MFC_DropDown = button
    }
    
    func removeDropDownCell() {
        MFC_DropDown?.removeFromSuperview()
    }

    @objc func dropDown(sender: UIButton)  {
        delegate?.dropDownClick!(sender: sender, cellIndex: MFC_indexPath!, tableTag: MFC_tableTag)
    }
    
    // MARK: - label
    /**
     label
     */
    func addLabelCell(title: String) {
        removeAll()
        
        let label = UILabel()
        label.text = title
        self.addSubview(label)
        label.topAlign(view: self)
        label.bottomAlign(view: self)
        label.leadingAlign(view: self, predicate: "20")
        label.trailingAlign(view: self, predicate: "-20")
        label.font = configure.shareConfigure.HMSize_15
        label.tintColor = UIColor.white
        
        MFC_label = label
    }
    
    func removeLabelCell() {
        MFC_label?.removeFromSuperview()
    }
    
    // MARK: - Radio
    /**
     Radio 单选
     */
    func addRadioCell(titles: Array<Any>) {
        removeAll()
        
        
        var buttons = Array<UIButton>()
        // 记录行数
        var rowNum = 0
        let num = (titles.count/2) + 1
        var i = 0
        for title in titles {
            let button  = UIButton()
            button.tag = i
            
            let h =   CGFloat(self.wHeight) - 16.0 // CGFloat(self.wHeight) / CGFloat(num) - 16.0
            let w = (self.wWidth - 60)/2
            button.titleLabel?.font = configure.shareConfigure.HMSize_15
            button.setTitleColor(UIColor.white, for: UIControlState.selected)
            button.setTitle((title as! String), for: UIControlState.normal)
            button.setTitleColor(UIColor.black, for: UIControlState.normal)
            button.layer.borderWidth = 1
            button.layer.cornerRadius = 4
            button.addTarget(self, action: #selector(selectorButton), for: UIControlEvents.touchUpInside)
            
            if button.tag == 0 {
                button.isSelected = true
                button.layer.borderColor = configure.shareConfigure.HMColor1.cgColor
                button.backgroundColor = configure.shareConfigure.HMColor1
            }else {
                button.isSelected = false
                button.layer.borderColor = UIColor.black.cgColor
                button.backgroundColor = UIColor.white
            }
            
            //奇偶
            let parity =  (i%2 == 0) ?  0  : 1
            
            if parity == 0 {
                // 如果是奇数加1
                rowNum += 1
            }
            // 10控制间距
            let y = ( ( h + 10) * CGFloat(rowNum)) -  (h) //h/4
              button.frame = CGRect.init(x: 20.0 * CGFloat(parity+1) + (w * CGFloat(parity)), y: y, width: w, height: h)
            self.addSubview(button)
            
            
            buttons.append(button)
            
            // 全部添加进去
           
            i += 1
            
        }
        
        
        MFC_Radio = buttons
        
        
        //单选内容
    }
    
    func removeRadioCell() {
        
        if MFC_Radio != nil {
            for radio in MFC_Radio! {
                let mfc_radio = radio as UIButton
                mfc_radio.removeFromSuperview()
            }
            MFC_Radio?.removeAll()
        }
        
  
    }
    
//    var radioBtn:
    
    @objc func selectorButton(sender: UIButton) {
        
        if radioBtnIndex == sender.tag {
            
        }else {
            let oldBt =  self.MFC_Radio![radioBtnIndex] as! UIButton
            oldBt.backgroundColor = UIColor.white
            oldBt.layer.borderColor = UIColor.black.cgColor
            oldBt.setTitleColor(UIColor.black, for: .normal)
            oldBt.isSelected = false
            
            
            let newBt =  self.MFC_Radio![sender.tag] as! UIButton
            newBt.backgroundColor = configure.shareConfigure.HMColor1
            newBt.layer.borderColor = configure.shareConfigure.HMColor1.cgColor
            newBt.setTitleColor(UIColor.white, for: .normal)
            newBt.isSelected = true
        }
        
        radioBtnIndex = sender.tag
     
        delegate?.radioClick!(sender: sender, cellIndex: MFC_indexPath!, tableTag: MFC_tableTag)
       
    }
    
    
    
    func removeAll() {
        removeFieldCell()
        removeLabelCell()
        removeButtonCell()
        removeSwitchCell()
        removeCircularCell()
        removeDropDownCell()
        removeRadioCell()
    }
    
    
    
    // MARK: - 初始化
    override func setupViews(view: UIView) {
        self.MFC_view = view
    }
    
    
    override func setJson(json: JSON) {
        type =  MFC_TYPE(rawValue: json["type"].stringValue)!  
        switch type {
        case .label:
            self.addLabelCell(title: json["value"].stringValue)
          //  MFC_label?.text = json["value"].stringValue
            
            break
        case .dropDown:
            self.addDropDownCell(title: json["value"].stringValue)
            // MFC_DropDown?.setTitle("\(json["value"].stringValue)", for: .normal)
      
            break
        case .button:
             self.addButtonCell(title: json["value"].stringValue)
            // MFC_Button?.setTitle("\(json["value"].stringValue)", for: .normal)
             
             break
        case .field:
             self.addFieldCell(title: json["value"].stringValue, placeholder: json["placeholder"].stringValue)
             MFC_fieldLable?.text = json["title"].stringValue
             
             break
        case .circular:
            self.addCircularCell(img: UIImage(named: json["value"].stringValue)!)
//            MFC_Circular?.imgName(name: "dagou.png")
            
            break
        case .switch:
 
           self.addSwitchCell(title: json["value"].stringValue, isOn: true)
           // 数据设置
           MFC_Switch?.isOn = json["isOn"].boolValue
           MFC_Switch?.tag = json["id"].intValue
           MFC_switchLabel?.text = json["value"].stringValue
           
            break
        case .radio:
            if json["title"] != JSON.null {
            self.addRadioCell(titles: json["title"].arrayObject!)
            
            }
            
            
            break
            
        case .checkbox:
            break 
//        default:
//             break
            //  MFC_label.text = json["text"].stringValue
            
        }
        
    }
    
    

}
extension MultiFunctionCell: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        delegate?.fieldChange?(sender: textField, text: string, cellIndex: MFC_indexPath!, tableTag: MFC_tableTag)
        return true
    }
}

